/*
 * @Author: wwssaabb
 * @Date: 2021-08-21 08:49:28
 * @LastEditTime: 2021-09-03 08:07:37
 * @FilePath: \hospitable-rental-for-react\src\utils\index.js
 */
import { reqCurrentCityName,reqCityInfo } from '../api'

export const cityKey='HKZF_CURRENT_CITY'
export const chooseCityKey='HKZF_CHOOSE_CITY'

export const getCurrentCity=async (mode)=>{ //获取当前的城市
  let localCity=JSON.parse(localStorage.getItem(cityKey))
  if(localCity&&mode!=='reset'){
    return Promise.resolve(localCity)
  }
  const res=await reqCurrentCityName()
  let infoRef=await reqCityInfo({name:res.data.city})
  let city={name:infoRef.body.label,id:infoRef.body.value}
  localStorage.setItem(cityKey,JSON.stringify(city))
  if(mode!=='reset')setChooseCity(city)
  return city
}

export const setChooseCity=async (city)=>{  //设置选择的城市
  if(typeof city==='string'){
    if(city===JSON.parse(localStorage.getItem(cityKey)).name){
      localStorage.setItem(chooseCityKey,localStorage.getItem(cityKey))
      return Promise.resolve()
    }
    return new Promise(async resolve=>{
      const infoRef=await reqCityInfo({name:city})
      localStorage.setItem(chooseCityKey,JSON.stringify({name:infoRef.body.label,id:infoRef.body.value}))
      resolve()
    })
  }else{
    localStorage.setItem(chooseCityKey,JSON.stringify(city))
  }
}

export const getChooseCity=()=>{  //获取选择的城市
  return JSON.parse(localStorage.getItem(chooseCityKey))
}



export const setUserData=(data)=>{  //设置用户登录数据，key=>USER
  localStorage.setItem('USER',JSON.stringify(data))
}

export const removeUserData=()=>{  //清除用户登录数据
  localStorage.removeItem('USER')
}

export const getUserData=()=>{  //获取用户的登录数据
  return JSON.parse(localStorage.getItem('USER'))
}

export const user_action={set:setUserData,get:getUserData,remove:removeUserData} //操作用户的登录数据的对象

export const setUserRecords=(records)=>{  //设置用户的看房记录
  localStorage.setItem('RECORDS',JSON.stringify(records))
}

export const addUserRecords=(data)=>{  //新增用户的看房记录
  let arr=getUserRecords()
  if(arr.findIndex(i=>i.houseCode===data.houseCode)===-1){
    let records=[data,...arr]
    localStorage.setItem('RECORDS',JSON.stringify(records))
  }
  
}

export const removeUserRecords=(records)=>{  //清空用户的看房记录
  localStorage.removeItem('RECORDS')
}

export const getUserRecords=()=>{  //获取用户的看房记录
  return JSON.parse(localStorage.getItem('RECORDS'))
}

export const records_action={set:setUserRecords,get:getUserRecords,remove:removeUserRecords,add:addUserRecords} //操作用户的看房记录的对象